package org.sidora.strata.context;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.UIManager;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Action;
import org.sidora.core.Sector;
import org.sidora.core.context.BuildedContext;
import org.sidora.core.context.Context;
import org.sidora.core.context.DeposedElement;
import org.sidora.core.context.DevastatedContext;
import org.sidora.core.context.EmptyedContext;
import org.sidora.core.context.Stratum;
import org.sidora.core.context.Surface;
import org.sidora.core.context.TechnicalContext;
import org.sidora.core.util.AbstractInventory;
import org.sidora.strata.SidoraTools;
import org.sidora.strata.Storage;

/**
 * Context Form Top Component wish displays context information
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class ContextFormTopComponent extends TopComponent {
    
    private static ContextFormTopComponent instance;
    /** path to the icon used by the component and its open action */
    static final String ICON_PATH = "org/sidora/resources/context16.png";
    
    private static final String PREFERRED_ID = "ContextFormTopComponent";
    
    private ContextFormTopComponent() {
        jPopupMenu = new JPopupMenu();
        System.setProperty(
            "Quaqua.tabLayoutPolicy","wrap"
         );
         // set the Quaqua Look and Feel in the UIManager
         try { 
              UIManager.setLookAndFeel(
                  "ch.randelshofer.quaqua.QuaquaLookAndFeel"
              );
         // set UI manager properties here that affect Quaqua
         
         } catch (Exception e) {
             // take an appropriate action here
             
         }
        
        initComponents();
        setName(NbBundle.getMessage(ContextFormTopComponent.class, "CTL_ContextFormTopComponent"));
        setToolTipText(NbBundle.getMessage(ContextFormTopComponent.class, "HINT_ContextFormTopComponent"));
        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldContext = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        addSectorMenu();
        jTextFieldSector = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldAction = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldFeature = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jTextFieldLocationInSector = new javax.swing.JTextField();
        jLabelType = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaInterpretation = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaDescription = new javax.swing.JTextArea();
        jTextFieldInterpretedType = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        jTextFieldDiggingMethod = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jTextFieldIntrusionRisk = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jTextFieldTakenMaterials = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jCheckBoxHasMaterialRemains = new javax.swing.JCheckBox();
        jCheckBoxHasSamples = new javax.swing.JCheckBox();
        jCheckBoxIsFinished = new javax.swing.JCheckBox();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, "Context:");

        jTextFieldContext.setEditable(false);
        jTextFieldContext.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jTextFieldContext.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldContextMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, "Sector:");

        jTextFieldSector.setEditable(false);
        jTextFieldSector.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldSectorMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel5, "Action:");

        jTextFieldAction.setEditable(false);
        jTextFieldAction.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldActionMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel6, "Feature:");

        jTextFieldFeature.setEditable(false);

        org.openide.awt.Mnemonics.setLocalizedText(jLabel8, "Location in sector:");

        jTextFieldLocationInSector.setEditable(false);
        jTextFieldLocationInSector.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldLocationInSectorMouseClicked(evt);
            }
        });

        jLabelType.setFont(new java.awt.Font("Lucida Grande", 1, 13)); // NOI18N
        jLabelType.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        org.openide.awt.Mnemonics.setLocalizedText(jLabelType, "Context");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel3)
                    .add(jLabel6)
                    .add(jLabel5)
                    .add(jLabel8))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldFeature, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldContext, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(jLabelType, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jLabel4)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jTextFieldSector, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))))
                    .add(jTextFieldAction, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE)
                    .add(jTextFieldLocationInSector, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 297, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldContext, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel3)
                    .add(jLabelType))
                .add(2, 2, 2)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldFeature, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel6)
                    .add(jTextFieldSector, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldAction, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel5))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel8)
                    .add(jTextFieldLocationInSector, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
        );

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, "Description:");

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, "Interpretation:");

        jTextAreaInterpretation.setBackground(new java.awt.Color(250, 240, 200));
        jTextAreaInterpretation.setColumns(20);
        jTextAreaInterpretation.setFont(new java.awt.Font("Georgia", 0, 13)); // NOI18N
        jTextAreaInterpretation.setLineWrap(true);
        jTextAreaInterpretation.setRows(5);
        jTextAreaInterpretation.setWrapStyleWord(true);
        jTextAreaInterpretation.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextAreaInterpretationFocusLost(evt);
            }
        });
        jScrollPane1.setViewportView(jTextAreaInterpretation);

        jTextAreaDescription.setBackground(new java.awt.Color(250, 240, 200));
        jTextAreaDescription.setColumns(20);
        jTextAreaDescription.setFont(new java.awt.Font("Georgia", 0, 13)); // NOI18N
        jTextAreaDescription.setLineWrap(true);
        jTextAreaDescription.setRows(5);
        jTextAreaDescription.setWrapStyleWord(true);
        jTextAreaDescription.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextAreaDescriptionFocusLost(evt);
            }
        });
        jScrollPane2.setViewportView(jTextAreaDescription);

        jTextFieldInterpretedType.setEditable(false);
        jTextFieldInterpretedType.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldInterpretedTypeMouseClicked(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel7, "Taken Materials:");

        jTextFieldDiggingMethod.setEditable(false);
        jTextFieldDiggingMethod.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldDiggingMethodMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel9, "Digging Method:");

        jTextFieldIntrusionRisk.setEditable(false);
        jTextFieldIntrusionRisk.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldIntrusionRiskMouseClicked(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel10, "Intrusion Risk:");

        jTextFieldTakenMaterials.setEditable(false);
        jTextFieldTakenMaterials.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldTakenMaterialsMouseClicked(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Management"));

        org.openide.awt.Mnemonics.setLocalizedText(jCheckBoxHasMaterialRemains, "Has material remains");
        jCheckBoxHasMaterialRemains.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jCheckBoxHasMaterialRemains.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jCheckBoxHasMaterialRemainsItemStateChanged(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jCheckBoxHasSamples, "Has samples");
        jCheckBoxHasSamples.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jCheckBoxHasSamples.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jCheckBoxHasSamplesItemStateChanged(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jCheckBoxIsFinished, "Is finished");
        jCheckBoxIsFinished.setMargin(new java.awt.Insets(0, 0, 0, 0));
        jCheckBoxIsFinished.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jCheckBoxIsFinishedItemStateChanged(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(15, 15, 15)
                .add(jCheckBoxHasMaterialRemains)
                .add(18, 18, 18)
                .add(jCheckBoxIsFinished)
                .add(18, 18, 18)
                .add(jCheckBoxHasSamples)
                .addContainerGap(56, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jCheckBoxIsFinished)
                    .add(jCheckBoxHasSamples)
                    .add(jCheckBoxHasMaterialRemains))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(jLabel10)
                    .add(jLabel9)
                    .add(jLabel7))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(jTextFieldTakenMaterials, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                        .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldDiggingMethod, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE)
                            .add(jTextFieldIntrusionRisk, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 309, Short.MAX_VALUE))
                        .addContainerGap())))
            .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldDiggingMethod, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel9))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldIntrusionRisk, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel10))
                .add(5, 5, 5)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jTextFieldTakenMaterials, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jLabel7))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextFieldInterpretedType, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(jLabel1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 399, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jTextFieldInterpretedType, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 142, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(15, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jTextFieldActionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldActionMouseClicked
        jPopupMenuActions.show(jTextFieldAction,evt.getX(),evt.getY());
    }//GEN-LAST:event_jTextFieldActionMouseClicked
    
    private void jCheckBoxIsFinishedItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxIsFinishedItemStateChanged
        //saveContextFields();
    }//GEN-LAST:event_jCheckBoxIsFinishedItemStateChanged
    
    private void jCheckBoxHasSamplesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxHasSamplesItemStateChanged
        //saveContextFields();
    }//GEN-LAST:event_jCheckBoxHasSamplesItemStateChanged
    
    private void jCheckBoxHasMaterialRemainsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBoxHasMaterialRemainsItemStateChanged
        //saveContextFields();
    }//GEN-LAST:event_jCheckBoxHasMaterialRemainsItemStateChanged
    
    private void jTextAreaInterpretationFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaInterpretationFocusLost
        //saveContextFields();
    }//GEN-LAST:event_jTextAreaInterpretationFocusLost

    private void jTextAreaDescriptionFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextAreaDescriptionFocusLost
        //saveContextFields();
    }//GEN-LAST:event_jTextAreaDescriptionFocusLost
    
    public void saveContextFields(){
        Context context = Storage.getContext();
        
        if (context != null){
            context.setDescription(jTextAreaDescription.getText());
            context.setInterpretation(jTextAreaInterpretation.getText());
            context.setHasMaterialReamins(jCheckBoxHasMaterialRemains.isSelected());
            context.setHasSamples(jCheckBoxHasSamples.isSelected());
            context.setFinished(jCheckBoxIsFinished.isSelected());
            saveMeasureSet();
            AbstractInventory.setObject(context);
        }
    }
    
    private void saveMeasureSet(){
        if (Storage.getContext() instanceof Stratum)
            Storage.getStratumTypeAction().saveStratumMeasures();       
        if (Storage.getContext() instanceof BuildedContext)
            Storage.getBuildedAction().saveBuildedmMeasures();
        if (Storage.getContext() instanceof EmptyedContext)
            Storage.getEmptyedAction().saveMeasures();
    }
    
    
    private void jTextFieldLocationInSectorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldLocationInSectorMouseClicked
        try {
            Field fiel = Context.class.getDeclaredField("locationInSector");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldLocationInSector);
            jPopupMenu.show(jTextFieldLocationInSector,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldLocationInSectorMouseClicked
    
    private void jTextFieldInterpretedTypeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldInterpretedTypeMouseClicked
        try {
            Field fiel = Context.class.getDeclaredField("interpretedType");
            jPopupMenu = SidoraTools.generatePopupMenuCategory(Storage.getContext(), fiel, jTextFieldInterpretedType);
            jPopupMenu.show(jTextFieldInterpretedType,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jTextFieldInterpretedTypeMouseClicked
    
    private void jTextFieldSectorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldSectorMouseClicked
        jPopupMenuSectors.show(jTextFieldSector,evt.getX(),evt.getY());
    }//GEN-LAST:event_jTextFieldSectorMouseClicked
    
    private void jTextFieldContextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldContextMouseClicked
        
        
    }//GEN-LAST:event_jTextFieldContextMouseClicked

private void jTextFieldDiggingMethodMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldDiggingMethodMouseClicked
        try {
            Field fiel = Context.class.getDeclaredField("diggingMethod");
            jPopupMenu = SidoraTools.generatePopupMenuCategorys(Storage.getContext(), fiel, jTextFieldDiggingMethod);
            jPopupMenu.show(jTextFieldDiggingMethod,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
}//GEN-LAST:event_jTextFieldDiggingMethodMouseClicked

private void jTextFieldIntrusionRiskMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldIntrusionRiskMouseClicked
        try {
            Field fiel = Context.class.getDeclaredField("intrusionRisk");
            jPopupMenu = SidoraTools.generatePopupMenuCategorys(Storage.getContext(), fiel, jTextFieldIntrusionRisk);
            jPopupMenu.show(jTextFieldIntrusionRisk,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
}//GEN-LAST:event_jTextFieldIntrusionRiskMouseClicked

private void jTextFieldTakenMaterialsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldTakenMaterialsMouseClicked
        try {
            Field fiel = Context.class.getDeclaredField("locationInSector");
            jPopupMenu = SidoraTools.generatePopupMenuCategorys(Storage.getContext(), fiel, jTextFieldTakenMaterials);
            jPopupMenu.show(jTextFieldTakenMaterials,evt.getX(),evt.getY());
        } catch (SecurityException ex) {
            ex.printStackTrace();
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        }
}//GEN-LAST:event_jTextFieldTakenMaterialsMouseClicked
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox jCheckBoxHasMaterialRemains;
    private javax.swing.JCheckBox jCheckBoxHasSamples;
    private javax.swing.JCheckBox jCheckBoxIsFinished;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabelType;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextAreaDescription;
    private javax.swing.JTextArea jTextAreaInterpretation;
    private javax.swing.JTextField jTextFieldAction;
    private javax.swing.JTextField jTextFieldContext;
    private javax.swing.JTextField jTextFieldDiggingMethod;
    private javax.swing.JTextField jTextFieldFeature;
    private javax.swing.JTextField jTextFieldInterpretedType;
    private javax.swing.JTextField jTextFieldIntrusionRisk;
    private javax.swing.JTextField jTextFieldLocationInSector;
    private javax.swing.JTextField jTextFieldSector;
    private javax.swing.JTextField jTextFieldTakenMaterials;
    // End of variables declaration//GEN-END:variables
    private JPopupMenu jPopupMenuSectors;
    private JPopupMenu jPopupMenu;
    private JPopupMenu jPopupMenuActions;
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized ContextFormTopComponent getDefault() {
        if (instance == null) {
            instance = new ContextFormTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the ContextFormTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized ContextFormTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find ContextForm component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof ContextFormTopComponent) {
            return (ContextFormTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        // TODO add custom code on component opening
    }
    
    public void componentClosed() {
        Storage.getChronoPropertiesAction().cerrar();
        Storage.getStrataPropertiesAction().cerrar();
        Storage.getDocsPropertiesAction().cerrar();
        Storage.getBuildedAction().cerrar();
        Storage.getDeposedAction().cerrar();
        Storage.getDevastedAction().cerrar();
        Storage.getEmptyedAction().cerrar();
        Storage.getStratumTypeAction().cerrar();
        Storage.getSurfaceAction().cerrar();
        Storage.getTechnicalAction().cerrar();
    }
    
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return ContextFormTopComponent.getDefault();
        }
    }
    
    private void ShowContextType(){
        if (Storage.getContext() == null){
            jLabelType.setText("");
        } else {
            jLabelType.setText(Storage.getContext().getStringClass());

            jLabelType.setIcon(Storage.getContext().getIcon());
            //jLabelType.setIcon(new javax.swing.ImageIcon(Storage.getContext().getIcon()));
        }   
    }
    
    public void fillContextItems(){
        emptyContextItems();
        
        Context context = Storage.getContext();
        if (context != null){
            jTextFieldContext.setText(context.toSmallString());
            if (context.getInterpretedType() != null){
                jTextFieldInterpretedType.setText(context.getInterpretedType().toString());
            }
            
            if (context.getLocationInSector() != null){
                jTextFieldLocationInSector.setText(context.getLocationInSector().toString());
            }
            
            jTextFieldFeature.setText(context.getFeatureString());
            jTextAreaDescription.setText(context.getDescription());
            jTextAreaInterpretation.setText(context.getInterpretation());
            jCheckBoxHasMaterialRemains.setSelected(context.hasMaterialRemains());
            jCheckBoxHasSamples.setSelected(context.hasSamples());
            jCheckBoxIsFinished.setSelected(context.isFinished());
            
            Storage.getChronoPropertiesAction().actionPerformed();
        }
        ShowContextType();
        
        addSectorMenu();
        fillSectorField();
        addActionMenu();
        fillActionField();
        showExtended();
    }
    
    public void showExtended(){
        if (Storage.getContext() instanceof Stratum){
            Storage.getStratumTypeAction().actionPerformed();
        }
        if (Storage.getContext() instanceof BuildedContext){
            Storage.getBuildedAction().actionPerformed();
        }
        if (Storage.getContext() instanceof DeposedElement){
            Storage.getDeposedAction().actionPerformed();
        }
        if (Storage.getContext() instanceof DevastatedContext){
            Storage.getDevastedAction().actionPerformed();
        }
        if (Storage.getContext() instanceof EmptyedContext){
            Storage.getEmptyedAction().actionPerformed();
        }
        if (Storage.getContext() instanceof Surface){
            Storage.getSurfaceAction().actionPerformed();
        }
        if (Storage.getContext() instanceof TechnicalContext){
            Storage.getTechnicalAction().actionPerformed();
        }
    }
    
    public void emptyContextItems(){
        jTextAreaDescription.setText("");
        jTextAreaInterpretation.setText("");
        jTextFieldAction.setText("");
        jTextFieldContext.setText("");
        jTextFieldFeature.setText("");
        jTextFieldInterpretedType.setText("");
        jTextFieldLocationInSector.setText("");
        jTextFieldSector.setText("");
    }
    
    protected void fillSectorField() {
        Context context = Storage.getContext();
        if (context!=null){
            
            
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = context.getSectors();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Sector asector = (Sector) iter.next();
                textbuffer.append(asector.getIdSector().getZone().getIdZone().toString()
                +"."+asector.getIdSector().getNumber().toString());
                
                if (iter.hasNext())
                    textbuffer.append("/");
            }
            textbuffer.append("]");
            
            jTextFieldSector.setText(textbuffer.toString());
        }
        
        
    }
    
    
    /////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    
    protected void addSectorMenu() {
        
        final Context context = Storage.getContext();
        if (context!=null){
            
            jPopupMenuSectors= new JPopupMenu();
            
            Set <Sector>sectors = context.getId().getZone().getSectors();
            Iterator<Sector> iter2 = sectors.iterator();
            int size = sectors.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Sector sector= (Sector) iter2.next();
                            if (sector!=null){
                                if (!sector.isClosed()){
                                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                    jcheck.setText(sector.toString());
                                    
                                    if (i==1)buff.append(sector.getIdSector().getNumber().toString()+"...");
                                    if (i==10)buff.append(sector.getIdSector().getNumber().toString());
                                    
                                    Iterator <Sector> iter4 = context.getSectors().iterator();
                                    while (iter4.hasNext()){
                                        Sector asector = (Sector) iter4.next();
                                        if (sector.equals(asector))jcheck.setSelected(true);
                                    }
                                    
                                    aJMenu.add(jcheck);
                                    
                                    jcheck.addMouseListener(new MouseAdapter(){
                                        public void mouseReleased(MouseEvent evt) {
                                            
                                            if(jcheck.getState()){
                                                
                                                context.getSectors().add(sector);
                                                if  (context.getFeature()!=null){
                                                    context.getFeature().setSectors(context.getSectors());
                                                }
                                                
                                                sector.getContexts().add(context);
                                            } else{
                                                
                                                context.getSectors().remove(sector);
                                                if  (context.getFeature()!=null){
                                                    context.getFeature().setSectors(context.getSectors());
                                                }
                                                sector.getContexts().remove(context);
                                            }
                                            fillSectorField();
                                            addSectorMenu();
                                            //TODO swingworker
                                            //SwingWorker worker = new SwingWorker() {
                                            //    public Object construct() {
                                            AbstractInventory.setObject(context);
                                            //        return "Context guardat";
                                            //    }
                                            //};
                                            //worker.start();
                                            
                                            
                                        }
                                    });
                                }
                            }
                            
                        }
                    }
                    aJMenu.setText(buff.toString());
                    jPopupMenuSectors.add(aJMenu);
                    
                }
            } else while (iter2.hasNext()){
                final Sector sector= (Sector) iter2.next();
                if (sector!=null){
                    if (!sector.isClosed()){
                        final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                        jcheck.setText(sector.toString());
                        
                        Iterator <Sector> iter4 = context.getSectors().iterator();
                        while (iter4.hasNext()){
                            Sector asector = (Sector) iter4.next();
                            if (sector.equals(asector))jcheck.setSelected(true);
                        }
                        
                        jPopupMenuSectors.add(jcheck);
                        
                        jcheck.addMouseListener(new MouseAdapter(){
                            public void mouseReleased(MouseEvent evt) {
                                
                                if(jcheck.getState()){
                                    
                                    context.getSectors().add(sector);
                                    if  (context.getFeature()!=null){
                                        context.getFeature().setSectors(context.getSectors());
                                    }
                                    
                                    sector.getContexts().add(context);
                                } else{
                                    
                                    context.getSectors().remove(sector);
                                    if  (context.getFeature()!=null){
                                        context.getFeature().setSectors(context.getSectors());
                                    }
                                    sector.getContexts().remove(context);
                                }
                                fillSectorField();
                                addSectorMenu();
                                //SwingWorker worker = new SwingWorker() {
                                //public Object construct() {
                                AbstractInventory.setObject(context);
                                //    return "Context guardat";
                                //    }
                                //};
                                //worker.start();
                                
                            }
                        });
                    }
                }}
            
        }
        
    }
    
    protected void addActionMenu() {
        
        final Context context = Storage.getContext();
        if (context != null){
            
            jPopupMenuActions = new JPopupMenu();
            List list = Action.Inventory.getList(Storage.getSite());
            TreeSet <Action> actions = new TreeSet<Action>();
            
            Iterator iter2 = list.iterator();
            while(iter2.hasNext()){
                actions.add((Action) iter2.next());
            }
            iter2 = actions.iterator();
            
            
            int size = actions.size();
            
            
            if (size>10){
                int smenus = ((size-1)/10)+1;
                
                for (int j=1; j<=smenus; j++){
                    JMenu aJMenu= new JMenu();
                    StringBuffer buff = new StringBuffer();
                    
                    for(int i = 1; i<=10; i++){
                        
                        if (iter2.hasNext()){
                            final Action action = (Action) iter2.next();
                            if (action!=null){
                                //if (!action.isClosed()){
                                final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                                jcheck.setText(action.toString());
                                
                                if (i==1)buff.append(action.toString()+"...");
                                if (i==10)buff.append(action.toString());
                                
                                Iterator <Action> iter4 = context.getActions().iterator();
                                while (iter4.hasNext()){
                                    Action aaction = (Action) iter4.next();
                                    if (action.equals(aaction))jcheck.setSelected(true);
                                }
                                
                                aJMenu.add(jcheck);
                                
                                jcheck.addMouseListener(new MouseAdapter(){
                                    public void mouseReleased(MouseEvent evt) {
                                        
                                        if(jcheck.getState()){
                                            context.getActions().add(action);
                                        } else{
                                            context.getActions().remove(action);
                                        }
                                        
                                        fillActionField();
                                        addActionMenu();
                                        
                                        AbstractInventory.setObject(context);
                                    }
                                });
                                //}
                            }
                            
                        }
                    }
                    aJMenu.setText(buff.toString());
                    jPopupMenuActions.add(aJMenu);
                    
                }
            } else while (iter2.hasNext()){
                final Action action= (Action) iter2.next();
                if (action!=null){
                    //if (!sector.isClosed()){
                    final JCheckBoxMenuItem jcheck = new JCheckBoxMenuItem();
                    jcheck.setText(action.toString());
                    
                    Iterator <Action> iter4 = context.getActions().iterator();
                    while (iter4.hasNext()){
                        Action aaction = (Action) iter4.next();
                        if (action.equals(aaction))jcheck.setSelected(true);
                    }
                    
                    
                    jPopupMenuActions.add(jcheck);
                    
                    jcheck.addMouseListener(new MouseAdapter(){
                        public void mouseReleased(MouseEvent evt) {
                            
                            if(jcheck.getState()){
                                context.getActions().add(action);
                            } else{
                                context.getActions().remove(action);
                            }
                            
                            fillActionField();
                            addActionMenu();
                            
                            AbstractInventory.setObject(context);
                            
                        }
                    });
                    //}
                }}
            
        }
        
    }
    
    public void fillActionField() {
        Context context = Storage.getContext();
        if (context != null){
            
            
            StringBuffer textbuffer = new StringBuffer("[");
            //Sector sector = context.getSectors().first();
            // System.out.println(sector);
            TreeSet set = context.getActions();
            boolean empty = set.isEmpty();
            Iterator iter = set.iterator();
            
            while (iter.hasNext()){
                Action aaction = (Action) iter.next();
                textbuffer.append(aaction.toString());
                
                if (iter.hasNext())
                    textbuffer.append("/");
            }
            textbuffer.append("]");
            
            jTextFieldAction.setText(textbuffer.toString());
        }
    }
}
